import { defineStore } from "pinia";

// 账号分类常量
export const ACCOUNT_CATEGORIES = [
  { id: "all", name: "全部", icon: "all" },
  { id: "social", name: "社交", icon: "social" },
  { id: "finance", name: "金融", icon: "finance" },
  { id: "game", name: "游戏", icon: "game" },
  { id: "entertainment", name: "娱乐", icon: "entertainment" },
  { id: "education", name: "学习", icon: "education" },
  { id: "work", name: "工作", icon: "work" },
  { id: "other", name: "其他", icon: "other" },
];

// 自动分类规则
const AUTO_CATEGORY_RULES = [
  { keywords: ["微信", "QQ", "微博", "知乎", "抖音", "小红书", "豆瓣", "推特", "Twitter", "Facebook", "Instagram", "Linkedin"], category: "social" },
  {
    keywords: ["银行", "支付宝", "理财", "基金", "股票", "证券", "招商", "建设", "工商", "农业", "中国银行", "交通银行", "邮政", "余额宝"],
    category: "finance",
  },
  { keywords: ["游戏", "网易", "腾讯", "暴雪", "Steam", "Epic", "Origin", "Xbox", "PlayStation", "NS", "Switch"], category: "game" },
  {
    keywords: ["视频", "音乐", "电影", "爱奇艺", "优酷", "腾讯视频", "哔哩哔哩", "B站", "网易云", "QQ音乐", "酷狗", "喜马拉雅", "咪咕", "影视"],
    category: "entertainment",
  },
  { keywords: ["学习", "教育", "课程", "慕课", "网课", "考试", "大学", "学校", "培训", "英语", "外语", "编程", "开发"], category: "education" },
  { keywords: ["工作", "公司", "企业", "办公", "邮箱", "邮件", "文档", "协作", "项目", "管理", "考勤", "打卡", "报销"], category: "work" },
];

// 自动分类函数
function autoDetectCategory(account) {
  const { name, username, website, description } = account;
  const text = `${name} ${username} ${website || ""} ${description || ""}`.toLowerCase();

  for (const rule of AUTO_CATEGORY_RULES) {
    for (const keyword of rule.keywords) {
      if (text.includes(keyword.toLowerCase())) {
        return rule.category;
      }
    }
  }

  return "other"; // 默认分类为其他
}

// 创建账号store
export const useAccountStore = defineStore("account", {
  // 状态
  state: () => ({
    accounts: [],
    searchKeyword: "",
    selectedCategory: "all",
  }),

  // 计算属性
  getters: {
    // 根据搜索关键词和选中分类过滤账号
    filteredAccounts: (state) => {
      let result = state.accounts;

      // 搜索过滤
      if (state.searchKeyword) {
        const keyword = state.searchKeyword.toLowerCase();
        result = result.filter((account) => {
          return (
            account.name.toLowerCase().includes(keyword) ||
            account.username.toLowerCase().includes(keyword) ||
            (account.website && account.website.toLowerCase().includes(keyword)) ||
            (account.description && account.description.toLowerCase().includes(keyword))
          );
        });
      }

      // 分类过滤
      if (state.selectedCategory !== "all") {
        result = result.filter((account) => account.category === state.selectedCategory);
      }

      // 按更新时间排序，最新的在前面
      return result.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
    },

    // 获取各分类的账号数量统计
    categoryStats: (state) => {
      const stats = {};

      // 初始化所有分类的计数为0
      ACCOUNT_CATEGORIES.forEach((category) => {
        stats[category.id] = 0;
      });

      // 计算各分类的账号数量
      state.accounts.forEach((account) => {
        stats[account.category]++;
        stats["all"]++;
      });

      return stats;
    },
  },

  // 操作方法
  actions: {
    // 添加账号
    addAccount(accountData) {
      const now = new Date().toISOString();
      const newAccount = {
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        ...accountData,
        category: accountData.category === "auto" ? autoDetectCategory(accountData) : accountData.category,
        createdAt: now,
        updatedAt: now,
      };

      this.accounts.push(newAccount);
      return newAccount;
    },

    // 更新账号
    updateAccount(id, accountData) {
      const index = this.accounts.findIndex((account) => account.id === id);
      if (index !== -1) {
        // 如果选择了自动分类，则重新检测分类
        const category = accountData.category === "auto" ? autoDetectCategory({ ...this.accounts[index], ...accountData }) : accountData.category;

        // 更新账号信息
        this.accounts[index] = {
          ...this.accounts[index],
          ...accountData,
          category,
          updatedAt: new Date().toISOString(),
        };

        return this.accounts[index];
      }
      return null;
    },

    // 删除账号
    deleteAccount(id) {
      const index = this.accounts.findIndex((account) => account.id === id);
      if (index !== -1) {
        this.accounts.splice(index, 1);
        return true;
      }
      return false;
    },

    // 设置搜索关键词
    setSearchKeyword(keyword) {
      this.searchKeyword = keyword;
    },

    // 设置选中的分类
    setSelectedCategory(categoryId) {
      this.selectedCategory = categoryId;
    },

    // 清空搜索和分类筛选
    clearSearch() {
      this.searchKeyword = "";
      this.selectedCategory = "all";
    },
  },

  // 持久化配置
  persist: {
    key: "account-store",
    paths: ["accounts"],
    storage: {
      getItem(key) {
        return uni.getStorageSync(key);
      },
      setItem(key, value) {
        uni.setStorageSync(key, value);
      },
      removeItem(key) {
        uni.removeStorageSync(key);
      },
    },
  },
});
